<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\AdminUserModel;
use App\Models\yb\CouponModel;
use App\Models\yb\GoodsModel;
use App\Models\yb\NetworkGoodsModel;
use App\Models\yb\GoodsOrderModel;
use App\Models\yb\GoodsTypeModel;
use App\Models\yb\SettingModel;
use App\Models\yb\UserAddressModel;
use App\Models\yb\UserCouponModel;
use App\Models\yb\GoodsContentModel;
use App\Models\yb\GoodsOrderDetailModel;
use App\Models\yb\UserModel;
use App\Models\yb\UserWaterTicketModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;


class GoodsController extends Controller
{

    /**
     * Get a JWT via given credentials.
     *  商品详情
     * @return \Illuminate\Http\JsonResponse
     */
    public function GoodsDetail(Request $request){

        $id = $request->post('id');

        if(empty($id)){
            return response()->json(['code'=>'201','msg' => '请选择商品']);
        }

        $network_id = $request->post('network_id');

        if(empty($network_id)){
            return response()->json(['code'=>'201','msg' => '请选择网点']);
        }

        $goods_data = GoodsModel::where(['id'=>$id])->first();

        $network_goods = NetworkGoodsModel::where(['goods_id'=>$goods_data['id'],'network_id'=>$network_id])->orderBy('goods_sales','desc')->first();

        if($network_goods['is_fictitious'] == 1){
            $goods_data['goods_sales'] = $network_goods['fictitious_goods_sales'];
        }else{
            $goods_data['goods_sales'] = $network_goods['goods_sales'];
        }

        $goods_content_data = GoodsContentModel::where(['status'=>1,'is_remord'=>1,'goods_id'=>$id])->orderBy('created_at','desc')->first();

        if(empty($goods_content_data)){
            $goods_content_data = GoodsContentModel::where(['status'=>1,'goods_id'=>$id])->orderBy('created_at','desc')->first();
        }

        $goods_data['content_count'] = GoodsContentModel::where(['status'=>1,'goods_id'=>$id])->count();
        $goods_content_data['user_list'] =  UserModel::where(['id'=>@$goods_content_data['user_id']])->first();
        $goods_data['goods_content_data'] = $goods_content_data;
        $goods_data['goods_cover'] = env('OSS_URL').$goods_data['goods_cover'];
        $goods_data['goods_type_name'] = GoodsTypeModel::selectValue('id',$goods_data['goods_type']);
        $goods_banner = $goods_data['goods_banner'];
        for($i=0;$i<count($goods_banner);$i++){
            $goods_banner[$i] = env('OSS_URL').$goods_banner[$i];
        }
        $goods_data['goods_banner'] = $goods_banner;
        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$goods_data]);
    }

    /**
     * Get a JWT via given credentials.
     *  商品下单详情
     * @return \Illuminate\Http\JsonResponse
     */
    public function OrderDetail(Request $request){

        $openid = $request->post('openid');
        $user_data = UserModel::where(['openid'=>$openid])->first();
        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $goods_list = $request->post('goods_id');
        if(empty($goods_list)){
            return response()->json(['code'=>'203','msg' => '请选择商品']);
        }

        $network_id = $request->post('network_id');
        if(empty($network_id)){
            return response()->json(['code'=>'203','msg' => '请选择网点']);
        }

        $network_data = AdminUserModel::where(['id'=>$network_id])->first();

        $start = $network_data['start_time'];
        $end =$network_data['end_time'];
        $start_hour = intval(explode(':', $start)[0]);
        $end_hour = intval(explode(':', $end)[0]);
        $service_time = [];
        while ($start_hour < $end_hour) {
            $service_time[]=str_pad($start_hour,2,0,STR_PAD_LEFT).':00-'.str_pad($start_hour+2,2,0,STR_PAD_LEFT).':00';
            $start_hour+=2;
        }

        $goods_list = json_decode($goods_list,true);

        $goods_id = array();
        foreach($goods_list as $key=>$val){
            $goods_id[$key] = $val['goods_id'];
        }

        $goods_data = GoodsModel::whereIn('id',$goods_id)->get();

        $coupon_data = array();

        $user_water_ticket_data = array();

        $total_price = 0;

        $setting_data = SettingModel::select('is_todoor_fee','todoor_fee_floor','todoor_amount','is_delivery_fee','delivery_fee')->first();

        foreach($goods_data as $key=>$val) {
            $total_price = $total_price+$val['goods_price'];
        }

        foreach($goods_data as $key=>$val){

            $goods_data[$key]['goods_cover'] = env('OSS_URL').$val['goods_cover'];

            $goods_data[$key]['number'] = $goods_list[$key]['number'];

            $goods_data[$key]['goods_type_name'] = GoodsTypeModel::selectValue('id',$val['goods_type']);

            $user_coupon_data = UserCouponModel::where(['user_id'=>$user_data['id'],'is_used'=>0,'status'=>1,'goods_type'=>$val['goods_type']])->where('promotion_full','<=',$val['goods_price']+0)->first();
            if(!empty($user_coupon_data)){
                $coupon_list = CouponModel::where((['id'=>$user_coupon_data['coupon_id']]))->first();

                $coupon_data[] = empty($coupon_list)?array():$coupon_list;
            }else{
               $coupon_data[] = array(); 
            }

          

            $user_water_ticket_list = UserWaterTicketModel::where(['user_id'=>$user_data['id'],'goods_id'=>$val['goods_warehouse_id']])->first();

            $user_water_ticket_data[] = empty($user_water_ticket_list)?array():$user_water_ticket_list;

            $goods_data[$key]['user_water_ticket_count'] = empty($user_water_ticket_list['number'])?0:$user_water_ticket_list['number'];

            if($setting_data['is_delivery_fee'] == 1 && $setting_data['delivery_fee']>=$total_price){
                $goods_data[$key]['delivery_fee'] = 0;
            }else{
                $goods_data[$key]['delivery_fee'] = $goods_data[$key]['freight'];
            }
            $goods_data[$key]['delivery_fee_name'] = "订单满".$setting_data['delivery_fee']."免配送费";

        }

        $user_address_data = UserAddressModel::where(['user_id'=>$user_data['id'],'is_default'=>1])->first();

        $data['goods_data'] = $goods_data;
        $data['setting_data'] = $setting_data;
        $data['user_address_data'] = empty($user_address_data)?array():$user_address_data;
        $data['coupon_data'] = $coupon_data;
        $data['user_water_ticket_data'] = $user_water_ticket_data;
        $data['service_time'] = $service_time;

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);

    }

    /**
     * Get a JWT via given credentials.
     *  订单列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function OrderListing(Request $request){
        $openid = $request->post('openid');
        $user_data = UserModel::where(['openid'=>$openid])->first();
        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $where['user_id'] = $user_data['id'];

        $status = $request->post('status');
        if($status != ''){
            $where['status'] = $status;
        }

        $page = $request->post('page', 1);

        $take = $request->post('take', 10);

        $setting_data = SettingModel::select(['customer_phone'])->first();

        $data = GoodsOrderModel::where($where)->orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();

        foreach($data as $key=>$val){
            $goods_order_detail = GoodsOrderDetailModel::where(['order_sn'=>$val['order_sn']])->get();

            foreach($goods_order_detail as $k=>$v){
                $goods_data = GoodsModel::where(['id'=>$v['goods_id']])->first();

                $goods_data['goods_cover'] = env('OSS_URL').$goods_data['goods_cover'];
                $goods_data['goods_type_name'] = GoodsTypeModel::selectValue('id',$goods_data['goods_type']);
                $goods_order_detail[$k]['goods_data'] = $goods_data;
            }

            $data[$key]['goods_order_detail']  = $goods_order_detail;
            $data[$key]['customer_phone']  = $setting_data['customer_phone'];
        }

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);

    }

    /**
     * Get a JWT via given credentials.
     *  订单详情
     * @return \Illuminate\Http\JsonResponse
     */
    public function OrderDetails(Request $request){
        $openid = $request->post('openid');
        $user_data = UserModel::where(['openid'=>$openid])->first();
        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $order_sn = $request->post('order_sn');

        $order_data = GoodsOrderModel::where(['order_sn'=>$order_sn])->first();
        if(empty($order_data)){
            return response()->json(['code'=>'203','msg' => '订单不存在']);
        }

        $goods_order_detail = GoodsOrderDetailModel::where(['order_sn'=>$order_data['order_sn']])->get();

        $setting_data = SettingModel::select('delivery_fee')->first();

        foreach($goods_order_detail as $k=>$v){
            $goods_data = GoodsModel::where(['id'=>$v['goods_id']])->first();
            $goods_data['goods_cover'] = env('OSS_URL').$goods_data['goods_cover'];
            $goods_data['goods_type_name'] = GoodsTypeModel::selectValue('id',$goods_data['goods_type']);
            $goods_order_detail[$k]['goods_data'] = $goods_data;
            if($v['freight'] >0){
                $goods_order_detail[$k]['delivery_fee'] = $v['freight'];
                $goods_order_detail[$k]['delivery_fee_name'] = "订单满".$setting_data['delivery_fee']."免配送费";
            }else{
                $goods_order_detail[$k]['delivery_fee'] = 0;
                $goods_order_detail[$k]['delivery_fee_name'] = "";
            }
        }

        $order_data['goods_order_detail']  = $goods_order_detail;

        $user_address_data = UserAddressModel::where(['id'=>$order_data['address_id']])->first();

        $setting_data = SettingModel::select(['customer_phone'])->first();


        $data['order_data'] = $order_data;
        $data['user_address_data'] = $user_address_data;
        $data['setting_data'] = $setting_data;

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);
    }

    /**
     * Get a JWT via given credentials.
     *  订单确认
     * @return \Illuminate\Http\JsonResponse
     */
    public function OrderConfirm(Request $request){
        $openid = $request->post('openid');
        $user_data = UserModel::where(['openid'=>$openid])->first();
        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $order_sn = $request->post('order_sn');

        $order_data = GoodsOrderModel::where(['order_sn'=>$order_sn])->first();

        if($order_data['status'] != 3){
            return response()->json(['code'=>'203','msg' => '订单已完成']);
        }

        AdminUserModel::where(['id'=>$order_data['network_id']])->increment('sales_volume',$order_data['amount']);

        GoodsOrderModel::where(['order_sn'=>$order_sn])->update(['status'=>4]);

        return response()->json(['code'=>'200','msg' => '请求成功']);
    }

    /**
     * Get a JWT via given credentials.
     *  订单删除
     * @return \Illuminate\Http\JsonResponse
     */
    public function OrderDelete(Request $request){
        $openid = $request->post('openid');
        $user_data = UserModel::where(['openid'=>$openid])->first();
        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $order_sn = $request->post('order_sn');

        $order_data = GoodsOrderModel::where(['order_sn'=>$order_sn])->first();

        if($order_data['status'] != 5){
            return response()->json(['code'=>'203','msg' => '订单不可删除']);
        }

        GoodsOrderModel::where(['order_sn'=>$order_sn])->delete();

        return response()->json(['code'=>'200','msg' => '请求成功']);
    }

    /**
     * Get a JWT via given credentials.
     *  商品评论
     * @return \Illuminate\Http\JsonResponse
     */
    public function OrderContentAdd(Request $request){
        $openid = $request->post('openid');
        $user_data = UserModel::where(['openid'=>$openid])->first();
        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $order_sn = $request->post('order_sn');

        $order_data = GoodsOrderModel::where(['order_sn'=>$order_sn])->first();

        if(empty($order_data)){
            return response()->json(['code'=>'203','msg' => '订单不存在']);
        }

        if($order_data['status'] != 4){
            return response()->json(['code'=>'203','msg' => '订单不可评论']);
        }

        if($order_data['is_content'] != 0){
            return response()->json(['code'=>'203','msg' => '您已评论']);
        }

        $content = $request->post('content');

        if(empty($content)){
            return response()->json(['code'=>'203','msg' => '请输入评论内容']);
        }

        $stars = $request->post('stars');

        if(empty($stars)){
            return response()->json(['code'=>'203','msg' => '请选择星级']);
        }

        $img = $request->post('img');

        GoodsContentModel::insert([
            'user_id' => $user_data['id'],
            'order_sn' => $order_sn,
            'goods_id' => $order_data['goods_id'],
            'content' => $content,
            'network_id' => $order_data['network_id'],
            'stars' => $stars,
            'img' => $img,
            'created_at'=>date('Y-m-d H:i:s',time())
        ]);

        GoodsOrderModel::where(['order_sn'=>$order_sn])->update([
            'is_content'=>1
        ]);


        return response()->json(['code'=>'200','msg' => '请求成功']);
    }

    /**
     * Get a JWT via given credentials.
     *  商品评论列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function ContentList(Request $request){

        $openid = $request->post('openid');
        $user_data = UserModel::where(['openid'=>$openid])->first();
        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $page = $request->post('page', 1);

        $take = $request->post('take', 10);

        $goods_id = $request->post('goods_id');

        $data = GoodsContentModel::where(['status'=>1,'goods_id'=>$goods_id])->orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();
        foreach ($data as $key=>$val){
            $data[$key]['user_list'] =  UserModel::where(['id'=>$val['user_id']])->first();
        }

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);

    }

    /**
     * Get a JWT via given credentials.
     *  订单评论
     * @return \Illuminate\Http\JsonResponse
     */
    public function OrderContent(Request $request){

        $openid = $request->post('openid');

        $user_data = UserModel::where(['openid'=>$openid])->first();

        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $order_sn = $request->post('order_sn');

        $data = GoodsContentModel::where(['order_sn'=>$order_sn])->first();

        $data['user_list'] = UserModel::where(['id'=>$user_data['user_id']])->first();

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);

    }

    /**
     * Get a JWT via given credentials.
     *  商品分类列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function TypeList(Request $request){
        
        $page = $request->post('page', 1);

        $take = $request->post('take', 10);

        $data = GoodsTypeModel::orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();
        foreach($data as $key=>$val){
            $data[$key]['icon'] = env('OSS_URL').$val['icon'];
            $data[$key]['select_icon'] = env('OSS_URL').$val['select_icon'];
        }

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);

    }


}
